// 场景管理器 - 管理多个场景并支持场景切换（只缓存当前场景）
import * as THREE from 'three';

export class SceneManager {
    constructor(container) {
        this.container = container;
        this.renderer = null;
        this.sceneFactories = new Map(); // 存储场景工厂函数
        this.currentScene = null; // 当前激活的场景实例（只保留一个）
        this.currentSceneName = null; // 当前场景名称
        this.clock = new THREE.Clock();
        this.animationId = null;
        
        // 相机视角模式
        this.isCameraViewActive = false; // 是否处于相机视角模式
        this.activeCameraNode = null; // 当前激活的相机节点
        this.editorCameraState = null; // 保存编辑器相机的状态
        this.rendererSize = new THREE.Vector2(); // 保存渲染器原始尺寸

        this.init();
    }

    init() {
        // 创建渲染器
        const width = window.innerWidth;
        const height = window.innerHeight;
        
        // 🔧 修复 Z-fighting：启用对数深度缓冲（logarithmicDepthBuffer）
        // 这可以大幅提高深度精度，减少深度冲突
        this.renderer = new THREE.WebGLRenderer({ 
            antialias: true,
            logarithmicDepthBuffer: true  // 启用对数深度缓冲
        });
        this.renderer.setSize(width, height);
        this.renderer.shadowMap.enabled = true;
        this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        this.container.appendChild(this.renderer.domElement);
        // 窗口自适应
        window.addEventListener('resize', this.onWindowResize.bind(this));

        // 不再注册默认场景，由项目配置动态注册场景

        // 启动动画循环
        this.animate();
    }

    // 注册新场景（传入工厂函数或场景类）
    registerScene(name, sceneFactory) {
        if (this.sceneFactories.has(name)) {
            console.warn(`⚠️ 场景 "${name}" 已存在，将被覆盖`);
        }
        
        // 如果传入的是类，转换为工厂函数
        const factory = typeof sceneFactory === 'function' && sceneFactory.prototype 
            ? () => new sceneFactory()
            : sceneFactory;
            
        this.sceneFactories.set(name, factory);
    }

    // 切换场景（销毁旧场景，创建新场景）
    switchScene(name) {
        // 退出相机视角模式
        if (this.isCameraViewActive) {
            this.exitCameraView();
        }
        
        if (!this.sceneFactories.has(name)) {
            console.error(`❌ 场景 "${name}" 不存在`);
            return false;
        }

        // 如果切换到相同场景，不做处理
        if (this.currentSceneName === name && this.currentScene) {
            return true;
        }

        // 销毁旧场景
        if (this.currentScene) {
            this.currentScene.deactivate();
            this.currentScene.dispose();
            this.currentScene = null;
        }

        // 创建新场景实例
        const sceneFactory = this.sceneFactories.get(name);
        const newScene = sceneFactory();
        
        // 初始化新场景
        newScene.init(this.renderer);
        
        // 激活新场景
        newScene.activate();
        this.currentScene = newScene;
        this.currentSceneName = name;
        return true;
    }

    // 获取当前场景
    getCurrentScene() {
        return this.currentScene;
    }

    // 获取所有已注册场景名称
    getSceneNames() {
        return Array.from(this.sceneFactories.keys());
    }
    
    // 获取当前场景名称
    getCurrentSceneName() {
        return this.currentSceneName;
    }

    // 窗口大小改变处理
    onWindowResize() {
        // 如果处于相机视角模式且分辨率模式为自定义/固定，则不跟随窗口调整渲染器尺寸
        // 但仍然需要调整容器布局（由CSS控制）
        if (this.isCameraViewActive) {
            this.updateCameraViewSize();
            return;
        }
        
        const width = window.innerWidth;
        const height = window.innerHeight;

        if (this.currentScene && this.currentScene.getCamera()) {
            const camera = this.currentScene.getCamera();
            camera.aspect = width / height;
            camera.updateProjectionMatrix();
        }

        this.renderer.setSize(width, height);
    }

    // 动画循环
    animate() {
        this.animationId = requestAnimationFrame(this.animate.bind(this));

        const deltaTime = this.clock.getDelta();

        // 更新当前场景
        if (this.currentScene && this.currentScene.isActive) {
            this.currentScene.update(deltaTime);
            
            // 确定使用哪个相机进行渲染
            let renderCamera = this.currentScene.getCamera();
            
            // 如果处于相机视角模式，使用选定的相机节点
            if (this.isCameraViewActive && this.activeCameraNode && this.activeCameraNode.object3D) {
                renderCamera = this.activeCameraNode.object3D;
            }
            
            this.renderer.render(
                this.currentScene.getScene(),
                renderCamera
            );
        }
    }
    
    // 手动触发一次渲染（用于材质更新等场景）
    render() {
        if (this.currentScene && this.currentScene.isActive) {
            // 确定使用哪个相机进行渲染
            let renderCamera = this.currentScene.getCamera();
            if (this.isCameraViewActive && this.activeCameraNode && this.activeCameraNode.object3D) {
                renderCamera = this.activeCameraNode.object3D;
            }
            
            this.renderer.render(
                this.currentScene.getScene(),
                renderCamera
            );
        }
    }

    /**
     * 进入相机视角模式
     * @param {TreeNode} cameraNode - 相机节点
     */
    enterCameraView(cameraNode) {
        if (!cameraNode || !cameraNode.object3D || !cameraNode.object3D.isCamera) {
            console.error('❌ 无效的相机节点');
            return;
        }
        
        this.isCameraViewActive = true;
        this.activeCameraNode = cameraNode;
        
        // 保存当前渲染器尺寸
        this.renderer.getSize(this.rendererSize);
        
        // 隐藏编辑器辅助元素
        if (this.currentScene) {
            // 隐藏网格、坐标轴等
            if (this.currentScene.scaleGrid) this.currentScene.scaleGrid.hide();
            // 隐藏所有CameraHelper
            this.currentScene.scene.traverse(obj => {
                if (obj.isCameraHelper) obj.visible = false;
            });
            // 禁用编辑器控制器
            if (this.currentScene.cameraController) {
                this.currentScene.cameraController.enabled = false;
            }
            // 禁用TransformControls
            if (this.currentScene.transformControlsManager) {
                this.currentScene.transformControlsManager.detach();
                this.currentScene.transformControlsManager.transformControls.enabled = false;
                this.currentScene.transformControlsManager.transformControls.visible = false;
            }
        }
        
        // 应用分辨率设置
        this.updateCameraViewSize();
        
        // 添加遮罩层（信箱模式）
        this.addCameraViewOverlay();
        
        console.log('🎥 进入相机视角模式');
    }
    
    /**
     * 退出相机视角模式
     */
    exitCameraView() {
        if (!this.isCameraViewActive) return;
        
        this.isCameraViewActive = false;
        this.activeCameraNode = null;
        
        // 1. 恢复渲染器尺寸到全屏
        this.renderer.setSize(window.innerWidth, window.innerHeight);
        
        // 2. 重置Canvas样式（清除transform和绝对定位的偏移）
        const canvas = this.renderer.domElement;
        canvas.style.width = '100%';
        canvas.style.height = '100%';
        canvas.style.position = 'absolute';
        canvas.style.top = '0';
        canvas.style.left = '0';
        canvas.style.margin = '0';
        canvas.style.transform = ''; // 关键：清除居中变换
        
        // 3. 恢复编辑器辅助元素
        if (this.currentScene) {
            if (this.currentScene.scaleGrid && this.currentScene.mode === 'edit') {
                this.currentScene.scaleGrid.show();
            }
            // 启用编辑器控制器
            if (this.currentScene.cameraController) {
                this.currentScene.cameraController.enabled = true;
            }
            // 启用TransformControls
            if (this.currentScene.transformControlsManager) {
                this.currentScene.transformControlsManager.transformControls.enabled = true;
                this.currentScene.transformControlsManager.transformControls.visible = true;
            }
        }
        
        // 移除遮罩层
        this.removeCameraViewOverlay();
        
        // 更新主相机投影矩阵
        if (this.currentScene && this.currentScene.getCamera()) {
            const camera = this.currentScene.getCamera();
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
        }
        
        console.log('🚪 退出相机视角模式');
    }
    
    /**
     * 更新相机视角尺寸（基于分辨率设置）
     */
    updateCameraViewSize() {
        if (!this.isCameraViewActive || !this.activeCameraNode) return;
        
        const cameraComponent = this.activeCameraNode.components.find(c => c.type === 'camera');
        const resolution = cameraComponent?.resolution || { mode: 'window', width: 1920, height: 1080 };
        
        let targetW, targetH;
        
        if (resolution.mode === 'window') {
            targetW = window.innerWidth;
            targetH = window.innerHeight;
        } else {
            targetW = resolution.width || 1920;
            targetH = resolution.height || 1080;
        }
        
        // 计算适配窗口的缩放尺寸（保持宽高比，类似object-fit: contain）
        const windowW = window.innerWidth;
        const windowH = window.innerHeight;
        const targetAspect = targetW / targetH;
        const windowAspect = windowW / windowH;
        
        let finalW, finalH;
        
        if (windowAspect > targetAspect) {
            // 窗口更宽，以高度为基准
            finalH = windowH;
            finalW = finalH * targetAspect;
        } else {
            // 窗口更高，以宽度为基准
            finalW = windowW;
            finalH = finalW / targetAspect;
        }
        
        // 更新渲染器尺寸（内部渲染分辨率）
        // 如果是固定分辨率，使用设定的分辨率进行渲染（可能比屏幕显示的高或低）
        if (resolution.mode !== 'window') {
            this.renderer.setSize(targetW, targetH, false); // false: 不改变 canvas style
        } else {
            this.renderer.setSize(windowW, windowH);
        }
        
        // 更新 Canvas 显示尺寸和位置（居中显示）
        const canvas = this.renderer.domElement;
        canvas.style.width = `${finalW}px`;
        canvas.style.height = `${finalH}px`;
        canvas.style.position = 'absolute';
        canvas.style.left = '50%';
        canvas.style.top = '50%';
        canvas.style.transform = 'translate(-50%, -50%)';
        canvas.style.margin = '0';
        
        // 更新相机宽高比
        if (this.activeCameraNode.object3D) {
            const camera = this.activeCameraNode.object3D;
            camera.aspect = targetW / targetH;
            camera.updateProjectionMatrix();
        }
    }
    
    /**
     * 添加相机视角遮罩层
     */
    addCameraViewOverlay() {
        let overlay = document.getElementById('camera-view-overlay');
        if (!overlay) {
            overlay = document.createElement('div');
            overlay.id = 'camera-view-overlay';
            overlay.style.cssText = `
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: #1e1e1e;
                z-index: -1; /* 在canvas后面 */
                pointer-events: none;
            `;
            this.container.insertBefore(overlay, this.renderer.domElement);
        }
    }
    
    /**
     * 移除相机视角遮罩层
     */
    removeCameraViewOverlay() {
        const overlay = document.getElementById('camera-view-overlay');
        if (overlay) {
            overlay.remove();
        }
    }

    // 停止动画
    stop() {
        if (this.animationId) {
            cancelAnimationFrame(this.animationId);
            this.animationId = null;
        }
    }

    // 清理所有资源
    dispose() {
        this.stop();
        
        // 清理当前场景
        if (this.currentScene) {
            this.currentScene.dispose();
            this.currentScene = null;
        }
        
        // 清空场景工厂
        this.sceneFactories.clear();
        this.currentSceneName = null;
        
        // 清理渲染器
        if (this.renderer) {
            this.renderer.dispose();
            if (this.renderer.domElement.parentNode) {
                this.renderer.domElement.parentNode.removeChild(this.renderer.domElement);
            }
        }
    }
}

// 导出便捷函数，保持向后兼容
export function setupScene(container) {
    const manager = new SceneManager(container);
    // 将管理器挂载到全局，方便调试和场景切换
    window.sceneManager = manager;
    return manager;
}